<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 5.4.2">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"xiaoqingming18.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.15.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="待解决问题1.基本类型是否可以获取对应的Class实例？ 什么是反射Java中的反射是指在运行时动态地获取类的信息以及调用它的方法和属性的能力。它允许程序在运行时检查和修改对象的内部状态，而不需要在编译时提前知道这些信息。 反射的主要作用包括：  动态创建对象：通过反射可以在运行时动态地创建一个类的对象，而不需要在编译时就确定类型。 动态调用方法：通过反射可以在运行时动态地调用一个类的方法，而不需">
<meta property="og:type" content="article">
<meta property="og:title" content="Java：反射">
<meta property="og:url" content="http://xiaoqingming18.github.io/2023/05/10/Java%EF%BC%9A%E5%8F%8D%E5%B0%84/index.html">
<meta property="og:site_name" content="鸣蜩十七">
<meta property="og:description" content="待解决问题1.基本类型是否可以获取对应的Class实例？ 什么是反射Java中的反射是指在运行时动态地获取类的信息以及调用它的方法和属性的能力。它允许程序在运行时检查和修改对象的内部状态，而不需要在编译时提前知道这些信息。 反射的主要作用包括：  动态创建对象：通过反射可以在运行时动态地创建一个类的对象，而不需要在编译时就确定类型。 动态调用方法：通过反射可以在运行时动态地调用一个类的方法，而不需">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-05-10T13:27:15.000Z">
<meta property="article:modified_time" content="2023-05-11T13:51:12.048Z">
<meta property="article:author" content="鸣蜩十七">
<meta property="article:tag" content="-Java基础 -反射">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://xiaoqingming18.github.io/2023/05/10/Java%EF%BC%9A%E5%8F%8D%E5%B0%84/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://xiaoqingming18.github.io/2023/05/10/Java%EF%BC%9A%E5%8F%8D%E5%B0%84/","path":"2023/05/10/Java：反射/","title":"Java：反射"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java：反射 | 鸣蜩十七</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">鸣蜩十七</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">鸣蜩十七是和女朋友谈恋爱的日子</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-schedule"><a href="/schedule/" rel="section"><i class="fa fa-calendar fa-fw"></i>日程表</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-commonweal"><a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
  </ul>
</nav>




</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BE%85%E8%A7%A3%E5%86%B3%E9%97%AE%E9%A2%98"><span class="nav-text">待解决问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%8F%8D%E5%B0%84"><span class="nav-text">什么是反射</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Class%E7%B1%BB-%E8%8E%B7%E5%8F%96%E6%9F%90%E4%B8%AA%E7%B1%BB%E7%9A%84%E4%BF%A1%E6%81%AF"><span class="nav-text">Class类-获取某个类的信息</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFClass%E7%B1%BB"><span class="nav-text">什么是Class类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BE%97%E5%88%B0Class%E7%B1%BB%E7%9A%84%E4%B8%80%E4%B8%AA%E5%AE%9E%E4%BE%8B"><span class="nav-text">得到Class类的一个实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Class%E7%B1%BB%E7%9A%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-text">Class类的常用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Class%E7%B1%BB%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%94%AF%E4%B8%80%E6%80%A7"><span class="nav-text">Class类对象的唯一性</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Field%E7%B1%BB%E3%80%81Method%E7%B1%BB%E5%92%8CConstructor%E7%B1%BB"><span class="nav-text">Field类、Method类和Constructor类</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">鸣蜩十七</p>
  <div class="site-description" itemprop="description">记录我的学习、生活和恋爱日常</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xiaoqingming18.github.io/2023/05/10/Java%EF%BC%9A%E5%8F%8D%E5%B0%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="鸣蜩十七">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="鸣蜩十七">
      <meta itemprop="description" content="记录我的学习、生活和恋爱日常">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java：反射 | 鸣蜩十七">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java：反射
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-05-10 21:27:15" itemprop="dateCreated datePublished" datetime="2023-05-10T21:27:15+08:00">2023-05-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-11 21:51:12" itemprop="dateModified" datetime="2023-05-11T21:51:12+08:00">2023-05-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">-后端</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="待解决问题"><a href="#待解决问题" class="headerlink" title="待解决问题"></a>待解决问题</h1><p>1.基本类型是否可以获取对应的Class实例？</p>
<h1 id="什么是反射"><a href="#什么是反射" class="headerlink" title="什么是反射"></a>什么是反射</h1><p><strong>Java中的反射是指在运行时动态地获取类的信息以及调用它的方法和属性的能力</strong>。它允许程序在运行时检查和修改对象的内部状态，而不需要在编译时提前知道这些信息。</p>
<p>反射的主要作用包括：</p>
<ol>
<li>动态创建对象：通过反射可以在运行时动态地创建一个类的对象，而不需要在编译时就确定类型。</li>
<li>动态调用方法：通过反射可以在运行时动态地调用一个类的方法，而不需要在编译时就确定方法名和参数类型。</li>
<li>获取类的信息：通过反射可以获取一个类的属性、构造方法、接口、父类等信息。</li>
<li>改变对象的属性值：通过反射可以在运行时改变一个对象的属性值。</li>
<li>框架开发：反射是许多框架(如Spring、Hibernate等)的核心功能之一，它们利用反射来实现各种复杂的功能。</li>
</ol>
<h1 id="Class类-获取某个类的信息"><a href="#Class类-获取某个类的信息" class="headerlink" title="Class类-获取某个类的信息"></a>Class类-获取某个类的信息</h1><h2 id="什么是Class类"><a href="#什么是Class类" class="headerlink" title="什么是Class类"></a>什么是Class类</h2><p>Java的<code>Class</code>类是用来描述Java类和接口的元数据(metadata)的。它提供了一些方法来获取一个类的信息，例如类名、父类、接口、字段、方法等。</p>
<h2 id="得到Class类的一个实例"><a href="#得到Class类的一个实例" class="headerlink" title="得到Class类的一个实例"></a>得到Class类的一个实例</h2><p>获取<code>Class</code>类对象的方法一共有3种：</p>
<p>第一种，通过<code>Object</code>类的<code>getClass()</code>方法返回一个<code>Class</code>实例：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Employee e;</span><br><span class="line"><span class="type">Class</span> <span class="variable">cl</span> <span class="operator">=</span> e.getClass();</span><br></pre></td></tr></tbody></table></figure>
<p>第二种，通过<code>Class</code>类的静态方法<code>forName()</code>获得类名对应的<code>Class</code>对象：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">className</span> <span class="operator">=</span> <span class="string">"java.util.Random"</span>;</span><br><span class="line"><span class="type">Class</span> <span class="variable">cl</span> <span class="operator">=</span> Class.forName(className);</span><br></pre></td></tr></tbody></table></figure>
<p>使用<code>forName()</code>方法是要注意，若要获取的类与当前类不在同一个包里，需要将要获取的类所在的包也要作为类名的一部分，如上例中的<code>java.util.Random</code>。</p>
<p><strong>第三种是一种更简便的方式</strong>，假设<code>T</code>是一个具体的类，可以通过<code>T.class</code>得到与之匹配的<code>Class</code>类对象：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Class</span> <span class="variable">cl</span> <span class="operator">=</span> Random.class;</span><br><span class="line"><span class="type">Class</span> <span class="variable">cl2</span> <span class="operator">=</span> <span class="type">int</span>.class;</span><br></pre></td></tr></tbody></table></figure>
<p>要注意的是，<strong>一个<code>Class</code>对象实际上表示的是一个类型，可能是类，也可能不是类。</strong>例如上面例子里的<code>int</code>不是类，但<code>int.class</code>是一个<code>Class</code>类型的对象。</p>
<h2 id="Class类的常用方法"><a href="#Class类的常用方法" class="headerlink" title="Class类的常用方法"></a>Class类的常用方法</h2><p><code>Class</code>类的一些常用方法包括：</p>
<ul>
<li><code>getName()</code>:返回类的名称；</li>
<li><code>getClassLoader()</code>:返回该类的加载器；</li>
<li><code>getDeclaredFields()</code>:返回该类的所有字段，包括继承而来的字段；</li>
<li><code>getDeclaredConstructors()</code>:返回该类的所有构造方法；</li>
<li><code>getDeclaredMethods()</code>:返回该类的所有方法，包括继承而来的方法；</li>
<li><code>isInterface()</code>:判断该类是否是一个接口；</li>
<li><code>isArray()</code>:判断该类是否是数组类型；</li>
<li><code>isPrimitive()</code>:判断该类是否是基本数据类型。</li>
</ul>
<p>通过这些方法，我们可以获取到Java类的各种信息，从而进行更加灵活和高效的编程。</p>
<h2 id="Class类对象的唯一性"><a href="#Class类对象的唯一性" class="headerlink" title="Class类对象的唯一性"></a>Class类对象的唯一性</h2><p>虚拟机为每一个Java类仅提供一个对应的<code>Class</code>对象。所以，可以用比较运算符<code>==</code>实现两个<code>Class</code>对象的比较：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(e.getClass() == Employee.class);</span><br></pre></td></tr></tbody></table></figure>
<p>上面的例子中，如果<code>e</code>是<code>Employee</code>类的实例，则表达式返回<code>true</code>，如果<code>e</code>不是<code>Employee</code>的一个实例，或者<code>e</code>是<code>Employee</code>的子类对象，则表达式返回<code>false</code>。</p>
<blockquote>
<p>Class类对象的唯一性指的是每个Java类都有且只有一个对应的Class对象，即一个类在内存中只能存在一份Class对象。这是因为Java中的类是按需加载的，当程序第一次使用某个类时，才会动态加载该类的字节码文件并创建对应的Class对象，因此每个类的Class对象都是唯一的。同时，由于Java中的多态特性，同一个类的不同对象可能会有不同的Class对象，但它们都指向同一个类的字节码文件。</p>
</blockquote>
<h1 id="Field类、Method类和Constructor类"><a href="#Field类、Method类和Constructor类" class="headerlink" title="Field类、Method类和Constructor类"></a>Field类、Method类和Constructor类</h1>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java%E5%9F%BA%E7%A1%80-%E5%8F%8D%E5%B0%84/" rel="tag"># -Java基础 -反射</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/05/09/%E5%88%B7%E9%A2%98%E7%AC%94%E8%AE%B0%EF%BC%9A%E7%89%9B%E5%AE%A2%E7%BD%91Java%E4%B8%93%E9%A1%B9%E7%BB%83%E4%B9%A0/" rel="prev" title="刷题笔记：牛客网Java专项练习">
                  <i class="fa fa-chevron-left"></i> 刷题笔记：牛客网Java专项练习
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/05/18/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%8E%9F%E7%90%86%EF%BC%9A%E6%95%B0%E6%8D%AE%E5%BA%93%E8%AE%BE%E8%AE%A1/" rel="next" title="数据库原理：数据库设计">
                  数据库原理：数据库设计 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">鸣蜩十七</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  




  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
